﻿#pragma once
#include <string>
#include "luaobj/LuaState.h"
#include "ZuiLib.h"

namespace ZuiLib
{


class LuaSysThread
{
public:
	ZUI_CLASS_NAME("zui.Thread");

	//运行的参数
	struct RunParam {
		uint32_t reqid;
		std::string script;
		std::string param;
	};

	//返回的参数
	struct ReturnParam :public ZuiLib::ZSchedulerBase {
		unsigned int reqid;
		unsigned int threadid;
		std::string param;

		void RunOnUIThread();
	};

    LuaSysThread();
	~LuaSysThread();

	//lua调用的接口
	void Start();
	void Run(RunParam *param);
	void Quit();

	virtual void OnRunning();

	unsigned int GetID() { return m_id; }

private:
	static int _ThreadProc(void* lpParameter);
	void _initLua();
	void _releaseLua();
	void _onReturn(ReturnParam* param);
	RunParam* _popRunParam();

	LuaOwnerState* m_luaState;
	SDL_Thread* m_thread;

	SDL_mutex* m_SleepMutex;
	SDL_cond* m_SleepCondition;

	SDL_mutex* m_mutex;
	std::queue<RunParam*> m_queue;
	volatile bool m_quit;

	unsigned int m_id;
};

void RegisterLuaThread(LuaState* L);

}//namespace

/*

--用法如下：
local thread=zui.Thread.new()
thread:start()

thread:run("print(arg) return arg","hello",function (rtn)
log(rtn)
end)

thread:run("print(arg) return arg","world!",function (rtn)
log(rtn)
thread:quit()
end)

*/